package com.dudu.control;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@ServerEndpoint("/order-ws/multiple/{orderId}/{typeId}/{userType}")
/**
 * 多人共用
 */
@Component
public class MultiuserController {
    static Map<Session, String> locationMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("orderId") String orderId, @PathParam("typeId") String typeId, @PathParam("userType") String userType) {
        locationMap.put(session, "");
        System.out.println("新连接：orderId=" + orderId + ", userId=" + typeId + ",userType=" + userType);
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        for (Session session1 : locationMap.keySet()) {
            String orderId = session1.getPathParameters().get("orderId");
            String userType = session1.getPathParameters().get("userType");
            if (orderId.equals(session.getPathParameters().get("orderId"))
                    && (!userType.equals(session.getPathParameters().get("userType")))) {
                session1.getAsyncRemote().sendText(message);
            }
        }
    }

    @OnError
    public void onError(Throwable error, Session session) {
        locationMap.remove(session);
        System.out.println("WebSocket 连接出错：orderId=" + session.getPathParameters().get("orderId") + ", userId=" + session.getPathParameters().get("userId") + ", driverId=" + session.getPathParameters().get("driverId"));
        error.printStackTrace();
    }

    @OnClose
    public void onClose(Session session) {
        locationMap.remove(session);
    }


}
